/*
 *  Filename: mpl3115.c
 *  Function: Sensor MPL3115
 *  Created: 2017-06-14
 *  Version: 1.0
 *  Author: Bin
 */

/*-------- Includes --------*/
#include <math.h>
#include "stm32f10x.h"

#include "i2c.h"
#include "mpl3115.h"

/*-------- Function prototypes --------*/
static void MPL3115_Write(uint8_t regAddr, uint8_t data);
static void MPL3115_Read(uint8_t regAddr, uint8_t *pdata);

/*-------- Private functions --------*/
void MPL3115_Write(uint8_t regAddr, uint8_t data)
{
    I2C_Start();
    I2C_WriteByte(MPL3115_ADDR);
    if (I2C_WaitAck())
        while (1);
    I2C_WriteByte(regAddr);
    if (I2C_WaitAck())
        while (1);
    I2C_WriteByte(data);
    if (I2C_WaitAck())
        while (1);
    I2C_Stop();
}

void MPL3115_Read(uint8_t regAddr, uint8_t *pdata)
{
    I2C_Start();
    I2C_WriteByte(MPL3115_ADDR);
    if (I2C_WaitAck())
        while (1);
    I2C_WriteByte(regAddr);
    if (I2C_WaitAck())
        while (1);

    I2C_Start();
    I2C_WriteByte(MPL3115_ADDR + 1);
    if (I2C_WaitAck())
        while (1);
    *pdata = I2C_ReadByte(0);
    I2C_Stop();
}

/*-------- Exported functions --------*/
void MPL3115_Init(void)
{
    // Intialize I2C
    I2C_Init();

    // Intialize MPL3115
    MPL3115_Write(0x26, 0xB8);      // set to Altimeter with an OSR = 128
    MPL3115_Write(0x13, 0x07);      // enable Data Flags in PT_DATA_CFG
    MPL3115_Write(0x26, 0xB9);      // set active
}

void MPL3115_Update(MPL3115_t *p)
{
    uint8_t status;

    // check status
    MPL3115_Read(MPL_STATUS, &status);
    if (status & 0x08) {
        uint8_t fraction;
        int8_t temp;
        uint16_t alti;

        // get Altitude
        MPL3115_Read(OUT_P_MSB, (uint8_t *)&alti + 1);
        MPL3115_Read(OUT_P_CSB, (uint8_t *)&alti);
        MPL3115_Read(OUT_P_LSB, &fraction);
        if ((fraction >>= 4) > 9)
            p->Alti = (float)alti + (float)fraction * 0.01f;
        else
            p->Alti = (float)alti + (float)fraction * 0.1f;

        // get Temperature
        MPL3115_Read(OUT_T_MSB, (uint8_t *)&temp);
        MPL3115_Read(OUT_T_LSB, &fraction);
        if ((fraction >>= 4) > 9)
            p->Temp = (float)temp + (float)fraction * 0.01f;
        else
            p->Temp = (float)temp + (float)fraction * 0.1f;
    }
}
